package org.ftc.report;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;

import org.apache.commons.lang3.StringUtils;
import org.docx4j.XmlUtils;
import org.docx4j.jaxb.Context;
import org.docx4j.model.fields.merge.DataFieldName;
import org.docx4j.model.fields.merge.MailMerger;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.Part;
import org.docx4j.wml.Br;
import org.docx4j.wml.ContentAccessor;
import org.docx4j.wml.ObjectFactory;
import org.docx4j.wml.P;
import org.docx4j.wml.R;
import org.docx4j.wml.Text;

public class Report12 {

	public static void main(String[] args) throws Exception {
		report3();
	}

	private static void report3() throws Exception {
		File test = new File("D:\\ftc\\1165\\test.docx");
		WordprocessingMLPackage testTemplate = WordprocessingMLPackage.load(test);
		Part part1 = testTemplate.getMainDocumentPart();
		List<Object> ps1 = getAllElementFromObject(part1, P.class);
		
		File tmp = new File("D:\\ftc\\1165\\紀錄(公報).docx");
		WordprocessingMLPackage template = WordprocessingMLPackage.load(tmp);
		// 變數

		Map<DataFieldName, String> map = new HashMap<>();
		map.put(new DataFieldName("sessionNo"), "9999");
		map.put(new DataFieldName("date"), "103年1月1日");

		System.out.println("===================================");
		Part part = template.getMainDocumentPart();
		List<Object> ps = getAllElementFromObject(part, P.class);

		P tempP = getTemplateP(ps, "committees");
		Map<String,String > map1 = new HashMap<>();
		map1.put("committees", "");
		P newP = cloneP(tempP, map1);
		ObjectFactory objFactory =  Context.getWmlObjectFactory();
		int count = 0;
		for(String strs: new String[]{"一委員一號","二委員二號","三委員三號","四委員四號"}){
			count++;
			R rspc = objFactory.createR();
			Text txt = objFactory.createText();
			txt.setValue(strs);
			rspc.getContent().add(txt);
			if(count !=4){
				Br br =  objFactory.createBr(); 
				rspc.getContent().add(br);
			}
			newP.getContent().add(rspc);
		}
		template.getMainDocumentPart().getContent().set(5, newP);
		
		tempP = getTemplateP(ps, "<<date>>");
		P newP2 = XmlUtils.deepCopy(tempP);
		template.getMainDocumentPart().getContent().add(newP2);
		
		
		MailMerger.performMerge(template, map, true);
		// WordprocessingMLPackage output =
		// MailMerger.getConsolidatedResultCrude(template,
		// Arrays.asList(map2,map7), true);
		template.save(new java.io.File("D:\\REPORT_12.docx"));
		System.out.println("end");
	}

	private static void cloneP(WordprocessingMLPackage template, List<Object> ps, String key, Map<String, String> map)
			throws Docx4JException, JAXBException {
		P tempP = getTemplateP(ps, key);
		List<Object> content = template.getMainDocumentPart().getContent();
		content.add(cloneP(tempP, map));
	}

	private static void removeP(WordprocessingMLPackage template, List<Object> ps, String[] strs)
			throws Docx4JException, JAXBException {
		for (String key : strs) {
			P tempP = getTemplateP(ps, key);
			template.getMainDocumentPart().getContent().remove(tempP);
		}
	}


	private static List<Object> getAllElementFromObject(Object obj, Class<?> toSearch) {

		List<Object> result = new ArrayList<Object>();
		if (obj instanceof JAXBElement)
			obj = ((JAXBElement<?>) obj).getValue();

		if (obj.getClass().equals(toSearch))
			result.add(obj);
		else if (obj instanceof ContentAccessor) {
			List<?> children = ((ContentAccessor) obj).getContent();
			for (Object child : children) {
				result.addAll(getAllElementFromObject(child, toSearch));
			}

		}
		return result;
	}

	private static P getTemplateP(List<Object> ps, String templateKey) throws Docx4JException, JAXBException {
		System.out.println("table size:" + ps.size());
		for (Iterator<Object> iterator = ps.iterator(); iterator.hasNext();) {
			Object p = iterator.next();
			System.out.println("=====================================");
			List<?> textElements = getAllElementFromObject(p, Text.class);
			for (Object text : textElements) {
				Text textElement = (Text) text;
				System.out.println("col value:" + textElement.getValue());
				if (StringUtils.equals(textElement.getValue(), templateKey))
					return (P) p;
			}
		}

		return null;
	}

	private static P cloneP(P p, Map<String, String> replacements) {
		System.out.println("begin clone");

		P tempP = (P) XmlUtils.deepCopy(p);
		List<?> textElements = getAllElementFromObject(tempP, Text.class);
		System.out.println("textElements size:" + textElements.size());
		for (Object object : textElements) {
			Text text = (Text) object;
			System.out.println("textValue:" + text.getValue());
			String replacementValue = (String) replacements.get(text.getValue());
			if (replacementValue != null) {
				System.out.println("replacement:" + replacementValue);
				text.setValue(replacementValue);
			}
		}
		return tempP;
	}

}
